package com.examiner.controller;

import com.alibaba.fastjson.JSON;
import com.examiner.bean.CommonPerson;
import com.examiner.bean.Department;
import com.examiner.result.EmptyObject;
import com.examiner.result.Result;
import com.examiner.service.CommonPersonService;
import com.examiner.service.DepartmentService;
import org.hibernate.Session;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/commonPersonAndDepartment")
public class CommonPersonAndDepartmentController {
    @Resource
    CommonPersonService commonPersonService;
    @Resource
    DepartmentService departmentService;

    @PersistenceContext
    private EntityManager entityManager;

    @PostMapping("/getCommonPersonAndDepartmentList/{superior}")
    public Result<Object> getCommonPersonAndDepartmentList(@PathVariable("superior") String superior){
        Map<String , Object> data = new HashMap<String,Object>();
        // 根据当前 父级 获取 用户及部门列表
        // 用户列表
        List<CommonPerson> commonPersonList = commonPersonService.getPersonList(superior);
        // 部门列表
        List<Department> departmentList = departmentService.getDepartmentList(superior);

        Session session = entityManager.unwrap(org.hibernate.Session.class);

        for (CommonPerson commonPerson : commonPersonList) {
            session.evict(commonPerson);
            commonPerson.setPassword("");
        }
        data.put("commonPersonList",commonPersonList);
        data.put("departmentList",departmentList);
        return Result.SUCCESS(data);
    }


    /**
     * 根据父级获取所有下级部门及成员0
     * @param superior
     * @return
     */
    @PostMapping("/getAllCAD/{superior}")
    public  Result<Object> getAllCND(@PathVariable("superior") String superior){
        // 根据当前 父级 获取 用户及部门列表
        List<Object> users;
        try {
            users = commonPersonService.getAllPersonList(superior);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.RESULT(201,"获取所有下级用户及部门失败",false,null);
        }
        return Result.SUCCESS(users);
    }

}
